<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 2016/3/21
 * Time: 14:34
 */

namespace front\modules\web\controllers;


use common\helpers\ReturnHelper;
use front\controllers\WebBaseController;
use goods\services\ShopService;
use order\services\OrderService;
use order\services\OrderUserService;
use order\services\RefundMapService;
use order\services\RefundNotesService;
use users\services\RegionService;
use Yii;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\web\Cookie;

class ReturngoodsController extends WebBaseController
{
    public $layout = 'main';
    /**
     * @return mixed
     * 退货申请列表
     */
    public function actionList()
    {
        $data = yii::$app->request->get();
        $data = [
            'getByWeb' => 1,
            'parent_order_id' => 0,
            'status_arr' => [5,6],
            'customer_id' => $this->getUserId()
        ];
        Yii::$app->request->queryParams = $data;
        $orders = OrderService::findOrder(Yii::$app->request->queryParams);
        $orderInfo = ArrayHelper::toArray($orders['result']);
        foreach ($orderInfo as $k => $info) {
            $itemData = [
                'order_id' => $info['order_id'],
                'is_return' => 0,
                'getByWeb' => 1
            ];
            $orderItem = OrderService::findItems($itemData);
            $itemInfo = ArrayHelper::toArray($orderItem);

            foreach ($itemInfo as $i => $item) {
                $refundInfo = RefundMapService::search([
                    'getByWeb' => 1,
                    'order_id' => $item['order_id'],
                    'product_id' => $item['product_id']
                ]);
                //查出此订单，此商品已申请退单数量
                $refund_num = count($refundInfo['result']);
                //差值为可申请数量
                $itemInfo[$i]['apply_num'] = $item['buy_num'] - $refund_num;
            }
            $orderInfo[$k]['item'] = $itemInfo;
        }
        return $this->render('list', [
            'orderInfo' => $orderInfo
        ]);
    }

    /**
     * @return mixed
     * 退货进度查看
     */
    public function actionRefund_list()
    {
        $data = yii::$app->request->get();
        $data = [
            'getByWeb' => 1,
            'customer_id' => $this->getUserId()
        ];
        Yii::$app->request->queryParams = $data;
        $refundInfo = RefundMapService::search(Yii::$app->request->queryParams);
        $refunds = ArrayHelper::toArray($refundInfo['result']);
        foreach ($refunds as $k => $v) {
            $itemData = [
                'order_id' => $v['order_id'],
                'product_id' => $v['product_id'],
                'getByWeb' => 1
            ];
            $orderItem = OrderService::findItems($itemData);
            $itemInfo = ArrayHelper::toArray($orderItem);
            //获取商品名称
            $refunds[$k]['product_title'] = $itemInfo[0]['product_title'];
            //获取退货留言信息
            $notesParams = [
                'getByWeb' => 1,
                'map_id' => $v['id'],
            ];
            $notesInfo = RefundNotesService::search($notesParams);
            $notes = ArrayHelper::toArray($notesInfo['result']);
            foreach ($notes as $n) {
                //组装客户退货原因
                if ($n['user_type'] == 1) {
                    $refunds[$k]['cst_note'] = $n['reason'];
                    continue;
                }
                //组装商家反馈信息
                if ($n['user_type'] == 2) {
                    $refunds[$k]['ser_note'] = $n['reason'];
                    continue;
                }
            }
            //获取退单状态
            $refunds[$k]['stat_char'] = self::getStatus($refunds[$k]['status']);
        }
        return $this->render('refund_list', [
            'refundInfo' => $refunds
        ]);
    }

    /**
     * @return mixed
     * 退货进度查看
     */
    public function actionApply()
    {
        $data = yii::$app->request->get();
        $order_id = $data['order_id'];
        $product_id = $data['product_id'];
        $retailer_id = $this->shop_id;
        $customer_id = $this->getUserId();

        if (Yii::$app->request->isAjax) {
            $getPost = yii::$app->request->post();
            if (isset($getPost['apply'])) {
                $params = [
                    'order_id' => $order_id,
                    'retailer_id' => $retailer_id,
                    'customer_id' => $customer_id,
                    'product_id' => $product_id,
                    'type' => $getPost['type'],
                    'reason' => $getPost['reason'],
                ];
                $cookies = \Yii::$app->response->cookies;
                $cookies->add(new Cookie([
                    'name' => 'refundParams',
                    'value' => $params,
                    'expire'=> time()+7000
                ]));
                return ReturnHelper::success_json('success');
            }else {
                return "信息不足~";
            }
        }
        $itemData = [
            'order_id' => $order_id,
            'product_id' => $product_id,
            'getByWeb' => 1
        ];
        $orderItem = OrderService::findItems($itemData);
        $itemInfo = ArrayHelper::toArray($orderItem);
        return $this->render('apply', [
            'itemInfo' => $itemInfo[0],
            'order_id' => $order_id,
            'product_id' => $product_id
        ]);
    }

    /**
     * @return mixed
     * 退货进度查看
     */
    public function actionApply_info()
    {
        $data = yii::$app->request->get();
        $order_id = $data['order_id'];
        $product_id = $data['product_id'];

        if (Yii::$app->request->isAjax) {
            $getPost = yii::$app->request->post();
            $refundParams = \Yii::$app->request->cookies->getValue('refundParams');
            if (!isset($refundParams)) {
                return "退单数据不足";
            }

            $params = [
                'order_id' => $refundParams['order_id'],
                'retailer_id' => $refundParams['retailer_id'],
                'customer_id' => $refundParams['customer_id'],
                'product_id' => $refundParams['product_id'],
                'type' => $refundParams['type'],
            ];
            $result = RefundMapService::add($params);
            if ($result['code'] == 0) {
                $noteParams = [
                    'map_id' => $result['result']['id'],
                    'user_id' => $refundParams['customer_id'],
                    'user_type' => 1,
                    'reason' => $refundParams['reason'],
                ];
                $noteRes = RefundNotesService::add($noteParams);
                if ($noteRes['code'] != 0) {
                    return $noteRes['message'];
                }
            }else{
                return $result['message'];
            }

            $getPost['id'] = $result['result']['id'];
            $model = new RefundMapService();
            $expressRes = $model->express($getPost);
            if ($expressRes['code'] == 0) {
                $cookies = \Yii::$app->response->cookies;
                $cookies->remove('refundParams');
                return 1;
            }else{
                return $expressRes['message'];
            }
        }

        $addrData = [
            'user_id' => $this->getUserId(),
            'default' => 1,
            'status' => 1,
            'getByWeb' => 1
        ];
        $addressInfo = OrderUserService::search($addrData);
        $address = ArrayHelper::toArray($addressInfo['result']);
        //获取地址具体信息
        if (isset($address[0]['district']) && $address[0]['district'] != 0) {
            $addrRes = self::getDistrict_char($address[0]['district']);
            $address[0]['district_char'] = $addrRes['district_char'];
            $address[0]['merger'] = $addrRes['merger'];
        }else {
            $address[0]['district_char'] = isset($address[0]['dist_cn_char'])? $address[0]['dist_cn_char'] : '';
            $address[0]['merger'] = isset($address[0]['dist_cn_char'])? $address[0]['dist_cn_char'] : '';
        }
        //获取退货商铺地址
        $shop = [];
        if (isset($data['shop_id'])) {
            $shopInfo = ShopService::getInfo($data['shop_id']);
            $shop = ArrayHelper::toArray($shopInfo);
            if (empty($shop)) {
                $shop = [
                    'shop_id' => 0
                ];
            }
        }else{
            $shop = [
                'shop_id' => 0
            ];
        }

        return $this->render('apply_info', [
            'order_id' => $order_id,
            'product_id' => $product_id,
            'address' => $address[0],
            'fromInfo' => $data,
            'shop' => $shop
        ]);
    }

    /**
     * get char
     * @return mixed
     * 获取地址具体信息
     */
    private static function getDistrict_char($district) {
        $pro = substr($district, 0 , 2);
        $city = substr($district, 0 , 4);
        $merger_name = RegionService::getMesgerName($district);
        $nameArr = explode(',', $merger_name);
        $ret['district_char'] = $pro . '|' . $city . '|' . $district . ',' . $nameArr[1] . '|' . $nameArr[2] . '|' . $nameArr[3];
        $ret['merger'] =  $nameArr[1] . '/' . $nameArr[2] . '/' . $nameArr[3];
        return $ret;
    }

    /**
     * get char
     * @return mixed
     * 获取退单状态
     */
    private static function getStatus($status) {
        $stat_char = [
            -1 => '未知状态',
            0 => '等待回复',
            1 => '商家同意退货',
            2 => '商家拒绝退货',
            3 => '正在退货中',
            4 => '放弃退货',
            5 => '退货完成',
        ];
        if (isset($stat_char[$status])) {
            return $stat_char[$status];
        }
        return $stat_char[-1];
    }
}